package com.haike.pushjobs.utils;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.text.csv.CsvData;
import cn.hutool.core.text.csv.CsvReadConfig;
import cn.hutool.core.text.csv.CsvUtil;
import cn.hutool.core.text.csv.CsvWriter;
import cn.hutool.core.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import lombok.var;

import java.io.File;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
public class CSVUtils {
    public static List<Map<String, Object>> parseCSV(String file_path) {
        CsvReadConfig config = CsvReadConfig.defaultConfig();
        config.setContainsHeader(true);

        var reader = CsvUtil.getReader(config);
//        String file_path="C:\\Users\\45363\\Desktop\\SML3km_HaiShiMaTou_2025080112.csv";
        CsvData csvData = reader.read(FileUtil.file(file_path), CharsetUtil.CHARSET_UTF_8);

        // 将 CSV 数据转换为 List<Map<String, Object>>
        List<Map<String, Object>> result_list = new ArrayList<>();
        var header = csvData.getHeader();
        for (List<String> row : csvData.getRows()) {
            Map<String, Object> row_map = new HashMap<>();
            for (int i = 0; i < header.size(); i++) {
                String key = header.get(i);
                key = key.replaceAll("\\(.*\\)", "").trim().toLowerCase();

                String value = row.get(i);
                row_map.put(key, value);
            }
            result_list.add(row_map);
        }
        return result_list;
    }

    public static void writeCSV(List<Map<String, Object>> dataList, String csvFilePath) {
        // 目标CSV文件路径

        // 使用Hutool转换
        try (CsvWriter csvWriter = new CsvWriter(new File(csvFilePath), Charset.defaultCharset())) {
            // 写入表头（从第一个Map的键获取）
            if (CollUtil.isNotEmpty(dataList)) {
                // dataList.get(0).keySet() 转成 String[]
                String[] headers = dataList.get(0).keySet().toArray(new String[0]);
                csvWriter.writeLine(headers);

                // 写入数据行
                for (Map<String, Object> map : dataList) {
                    List<String> values = new ArrayList<>();
                    for (String header : headers) {
                        values.add(MapUtil.getStr(map, header));
                    }
                    csvWriter.writeLine(values.toArray(new String[0]));
                }
            }
            log.info("CSV文件生成成功！. csv文件: {}", csvFilePath);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("CSV文件生成失败：{}", e.getMessage());
        }
    }

    public static void main(String[] args) {
        // 示例数据：List<Map>
        List<Map<String, String>> dataList = new ArrayList<>();
        Map<String, String> map1 = new HashMap<>();
        map1.put("name", "张三");
        map1.put("age", "25");
        map1.put("city", "北京");
        dataList.add(map1);

        Map<String, String> map2 = new HashMap<>();
        map2.put("name", "李四");
        map2.put("age", "30");
        map2.put("city", "上海");
        dataList.add(map2);

        // 目标CSV文件路径
        String csvFilePath = "hutool_data.csv";

        // 使用Hutool转换
        try (CsvWriter csvWriter = new CsvWriter(new File(csvFilePath), Charset.defaultCharset())) {
            // 写入表头（从第一个Map的键获取）
            if (CollUtil.isNotEmpty(dataList)) {
                // dataList.get(0).keySet() 转成 String[]
                String[] headers = dataList.get(0).keySet().toArray(new String[0]);
                csvWriter.writeLine(headers);

                // 写入数据行
                for (Map<String, String> map : dataList) {
                    List<String> values = new ArrayList<>();
                    for (String header : headers) {
                        values.add(map.getOrDefault(header, ""));
                    }
                    csvWriter.writeLine(values.toArray(new String[0]));
                }
            }
            System.out.println("CSV文件生成成功！");
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("CSV文件生成失败：" + e.getMessage());
        }
    }
}
